<?php

namespace app\teacher\controller\v1;

use app\common\controller\BaseController;
use app\teacher\model\Tag as TagModel;
use app\teacher\validate\BusyTimeValidate;
use app\teacher\validate\CreateCourseValidate;
use app\teacher\validate\ExperienceValidate;
use think\Db;
use app\teacher\model\Teacher as TeacherModel;
use app\teacher\model\TeacherCourse as TeacherCourseModel;
use app\teacher\model\TeacherTag as TeacherTagModel;
use app\teacher\model\TeachingExperience as TeachingExperienceModel;
use app\teacher\model\TeacherBusy as TeacherBusyModel;
use app\teacher\model\Course as CourseModel;
use app\teacher\model\CourseOrder as CourseOrderModel;
use app\teacher\model\User as UserModel;


class Course extends BaseController
{
    /**
     * 新增课程
     */
    public function create(CreateCourseValidate $createCourseValidate,
                           ExperienceValidate $experienceValidate,
                           TeacherCourseModel $teacherCourseModel,
                           TeacherBusyModel $teacherBusyModel)
    {
        $this->isPost();
        $data = $this->request->post();
        $this->paramValidate($createCourseValidate, $data);
        $data['teacher_id'] = $this->teacherId;
        $teacher = TeacherModel::find($data['teacher_id']);
        if (!$teacher) {
            $this->errorMsg(20000);
        }
        if (isset($data['experience'])) {
            foreach ($data['experience'] as $val) {
                $this->paramValidate($experienceValidate, $val);
            }
        }

        Db::startTrans();
        try {
            //新增课程
            $teacherCourseModel->add($data);
            //更新教师地址，经纬度
            $teacher->address = $data['address'];
            $teacher->longitude = $data['longitude'];
            $teacher->latitude = $data['latitude'];
            $teacher->trait = $data['trait'] ?? '';

            //新增忙碌时间
            $data['busy_time']['teacher_id'] = $data['teacher_id'];
            $teacherBusyModel->add($data['busy_time']);
            //标签
            if (isset($data['tag']) && $data['tag']) {
                TeacherTagModel::add($data['teacher_id'], $data['tag']);
            }
            //教学经历
            if (isset($data['experience']) && $data['experience']) {
                $experienceData = TeachingExperienceModel::addData($data['teacher_id'], $data['experience']);
                TeachingExperienceModel::insertAll($experienceData);
                //更新年份
                $startTime = $experienceData ? min(array_column($experienceData, 'starttime')) : 0;
                $teacher->year = $startTime > 0 ? date('Y', $startTime) : '';
            }
            $teacher->save();

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
        }
        isset($e) ? $this->error($e->getMessage()) : $this->success();
    }

    /**
     * 编辑
     */
    public function edit(TeacherBusyModel $teacherBusyModel)
    {
        $this->isPost();
        $data = $this->request->post();
        $teacherId = $this->teacherId;
        $teacher = TeacherModel::find($teacherId);
        if (!$teacher) {
            $this->errorMsg(20000);
        }
        $teachCourse = TeacherCourseModel::find($data['teacher_course_id'] ?? 0);
        if (!$teachCourse) {
            $this->errorMsg(10008);
        }

        Db::startTrans();
        try {
            //更新教师
            $teacher->allowField(true)->save($data);
            //更新课程
            $teachCourse->allowField(true)->save($data);
            //新增忙碌时间
            $teacherBusy = TeacherBusyModel::getTeacherTime($teacherId);
            if (!$teacherBusy) {
                $data['teacher_id'] = $teacherId;
                $teacherBusyModel->add($data['busy_time']);
            } else {
                $teacherBusy->allowField(true)->save($data['busy_time']);
            }

            if (isset($data['tag'])) {
                //删除标签
                TeacherTagModel::deleteTag($teacherId);
                //添加标签
                TeacherTagModel::add($teacherId, $data['tag']);
            }
            if (isset($data['experience'])) {
                //删除教学经历
                TeachingExperienceModel::deleteExperience($teacherId);
                //教学经历
                $experienceData = TeachingExperienceModel::addData($teacherId, $data['experience']);
                TeachingExperienceModel::insertAll($experienceData);
                //更新年份
                $startTime = $experienceData ? min(array_column($experienceData, 'starttime')) : 0;
                $teacher->year = $startTime > 0 ? date('Y', $startTime) : '';
                $teacher->save();
            }

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
        }
        isset($e) ? $this->error($e->getMessage()) : $this->success();
    }



    /**
     * 标签
     */
    public function tag()
    {
        $tags = TagModel::getTags();
        $this->success('', compact('tags'));
    }

    /**
     * 课程记录
     */
    public function index()
    {
        $date = $this->notEmpty('date');
        $courses = CourseModel::getCourses($this->teacherId, date('Y-m-d', strtotime($date)));
        $this->success('', $courses);
    }

    /**
     * 课次详情
     */
    public function read()
    {
        $courseId = $this->notEmpty('course_id');
        $course = CourseModel::getByCourseId($courseId);
        if (!$course) {
            $this->errorMsg(14000);
        }
        $course['user'] = UserModel::getUserInfo($course->user_id);
        $this->success('', compact('course'));
    }

    /**
     * 全部预约课程进度
     */
    public function degree()
    {
        $courseOrderId = $this->notEmpty('course_order_id');
        $course = CourseModel::getAllReserve($courseOrderId);
        $courseCount = CourseModel::getAllCourseCounts($courseOrderId);
        $this->success('', [
            'course' => $course,
            'course_count' => $courseCount
        ]);
    }

    /**
     * 预约 - 完成课程进度
     */
    public function finish()
    {
        $courseOrderId = $this->notEmpty('course_order_id');
        $course = CourseModel::getOrtherFinish($courseOrderId);
        $courseCount = CourseModel::getAllCourseCounts($courseOrderId);
        $course['course_count'] = $courseCount;
        $this->success('', $course);
    }

    /**
     * 授课记录
     */
    public function log()
    {
        $size = $this->request->get('size');
        $teacherId = $this->teacherId;
        $teacherCourseId = TeacherCourseModel::getColumnByTeacherId($teacherId, 'teacher_course_id');
        //课程记录
        $courses = CourseModel::getFinishLog($teacherCourseId, $size);
        //累积天数
        $days = CourseModel::getDays($teacherCourseId);
        //累积课时
        $times = CourseModel::getFinishTimes($teacherCourseId);
        $hours = CourseModel::getHours($times);
        //累积课次
        $courseCount = count($times);
        //累积订单
        $orderCount = CourseOrderModel::getFinishCount($teacherCourseId);
        $courses->total() ? $this->success('', [
            'courses' => $courses->items(),
            'total' => $courses->total(),
            'days' => $days,
            'hours' => $hours,
            'course_count' => $courseCount,
            'order_count' => $orderCount
        ]) : $this->notFoundData();
    }

}
